﻿using System;
using System.Collections.Generic;
using NpcFramework;
using UnityEngine;
using UnityEngine.Serialization;

namespace Yoozoo.Gameplay.Liberty.AI
{
    public enum TrafficLightState
    {
        Green = 1,
        Yellow = 2,
        Red = 3,
    }
    
    public class TrafficLightController : MonoBehaviour
    {
        public static Action<TrafficLightController> onEnableTrafficLight;
        
        public int trafficLightId;

        public List<TriggerLightJunction> junctions;
        [Header("人行道路线")]
        public List<NpcWayPath> lightPaths;

        public float greenLightTime = 10f;
        public float yellowLightTime = 3f;

        [SerializeField]
        private float _lightTimer = 0f;
        [SerializeField]
        private int _curJunctionIndex = 0;
        [SerializeField]
        private bool _waiting = false;

        private void Awake()
        {
            onEnableTrafficLight?.Invoke(this);
        }

        void Update ()
        {
            _lightTimer += Time.deltaTime;

            //time for green light is over, change states on current and next traffic lights
            if(!_waiting && _lightTimer >= greenLightTime)
            {
                // 当前绿灯--> 黄灯
                junctions[_curJunctionIndex].SwitchGreenState(false);				// free: 绿灯
                junctions[_curJunctionIndex].SwitchYellowState(true);				// waiting：黄灯

                if(_curJunctionIndex == junctions.Count - 1)
                    _curJunctionIndex = 0;
                else
                    _curJunctionIndex ++;

                junctions[_curJunctionIndex].SwitchYellowState(true);

                _waiting = true;
            }

            //time for yellow light is over, change states on current and next traffic lights
            if(_waiting && _lightTimer >= greenLightTime + yellowLightTime)
            {
                if(_curJunctionIndex == 0)
                    junctions[junctions.Count - 1].SwitchYellowState(false);
                else
                    junctions[_curJunctionIndex - 1].SwitchYellowState(false);		// 变红灯

                junctions[_curJunctionIndex].SwitchYellowState(false);
                junctions[_curJunctionIndex].SwitchGreenState(true);					// 变绿灯

                _waiting = false;
                _lightTimer = 0.0f;
            }
        }


#if UNITY_EDITOR

        private void OnValidate()
        {
            transform.name = $"TrafficLight_{trafficLightId}";
        }

#endif
        
    }
}